package com.sgidi.einvoice.web;

import com.sgidi.einvoice.models.InvoiceResult;
import com.sgidi.einvoice.service.FileConversionService;
import com.sgidi.einvoice.service.WordSigner;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/word")
public class WordController {

    @PostMapping(value = "/sign")
    public ResponseEntity<byte[]> extract(@RequestParam("file") MultipartFile file, String partyidcount, String keyword){

        ByteArrayOutputStream out =  WordSigner.SignWord(file,partyidcount,keyword,false);
        byte[] pdfWithSignatureBytes = out.toByteArray();
        return ResponseEntity.ok()
                .contentLength(pdfWithSignatureBytes.length)
                .contentType(org.springframework.http.MediaType.valueOf("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
                .body(pdfWithSignatureBytes);
    }

    @PostMapping(value = "/signbyname")
    public ResponseEntity<byte[]> extractByName(@RequestParam("file") MultipartFile file, String partyidcount,String keyword){
        ByteArrayOutputStream out =  WordSigner.SignWord(file,partyidcount,keyword,true);
        byte[] pdfWithSignatureBytes = out.toByteArray();
        return ResponseEntity.ok()
                .contentLength(pdfWithSignatureBytes.length)
                .contentType(org.springframework.http.MediaType.valueOf("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
                .body(pdfWithSignatureBytes);
    }

    @PostMapping("/mergeFilesToWord")
    public ResponseEntity<byte[]> mergeFilesToPdf(
            @RequestParam("files") List<MultipartFile> files)
            throws IOException {

        FileConversionService fileConversionService = new FileConversionService();
        return fileConversionService.handleFileUploadByWord(files);
    }
}
